package com.openatc.agent.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author ：zhangwenchao
 * @date ：Created in 2023/2/16 16:57
 * @description：回调函数线程池
 * @modified By：
 * @version: $
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Value("${agent.comm.thread.count.report}")
    private int reportThreadCount;

    /**
     * 允许的空闲时间
     * 默认为60
     */
    private int keepAlive = 300;

    @Bean
    public TaskExecutor taskExecutor() {

        /**
         * 每秒需要多少个线程处理
         * tasks/(1/taskcost)
         */
        int corePoolSize = reportThreadCount;


        /**
         * 线程池维护线程的最大数量
         * (max(tasks)- queueCapacity)/(1/taskcost)
         */
        int maxPoolSize = reportThreadCount;

        /**
         * 缓存队列
         * (coreSizePool/taskcost)*responsetime
         */
        int queueCapacity = reportThreadCount*2;

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //设置队列容量
        executor.setQueueCapacity(queueCapacity);
        //设置允许的空闲时间（秒）
        //executor.setKeepAliveSeconds(keepAlive);
        //设置默认的线程名称
        executor.setThreadNamePrefix("thread-");
        //设置拒绝策略rejection-policy：当pool已经达到max size的时候，如何处理新任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}
